package com.atguigu.channel;

import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.util.Objects;

/**
 * className: FileChannelDemo1
 * description:
 * date: 2023/3/8 0008-17:06
 * <p>
 * project: nio
 * package: com.atguigu.channel
 * email: 1085844536@qq.com
 * version:
 *
 * @author WangGuojian
 */
public class FileChannelDemo1 {

    /**
     * FileChannel 读取数据到 buffer 中
     *
     * @param args {@link String[]}
     */
    public static void main(String[] args) throws IOException {
        // 创建 FileChannel
        RandomAccessFile aFile = new RandomAccessFile(Objects.requireNonNull(
                FileChannelDemo1.class.getClassLoader().getResource("01.txt")).getPath(), "rw");
        FileChannel channel = aFile.getChannel();

        // 创建 Buffer
        ByteBuffer buf = ByteBuffer.allocate(1024);

        // 读取数据到 buffer 中
        int bytesRead = channel.read(buf);
        while (bytesRead != -1) {
            System.out.println("读取了:" + bytesRead);
            buf.flip();
            while (buf.hasRemaining()) {
                System.out.println(((char) buf.get()));
            }
            buf.clear();
            bytesRead = channel.read(buf);
        }
        aFile.close();
        System.out.println("结束了");
    }
}
